package cn.kgc.task;

import cn.kgc.entity.Messageinfo;
import cn.kgc.service.SenderMessageInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author wangyue
 * @version 1.0
 */
@Slf4j
@Component
@EnableScheduling
public class TimerTask {
    @Value("${mq.maxResend}")
    private int maxResend;
    @Resource
    private SenderMessageInfoService senderMessageInfoService;
    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 每隔一段时间查询数据库中那些没有成功发送到消息队列中的消息,重新发送
     */
    @Scheduled(
        fixedRateString = "${mq.fixedRate}"
    )
    public void task1(){
        //1 查询没有成功发送到消息队列中的消息
        List<Messageinfo> messageinfos = senderMessageInfoService.listReadyMessage();
        //2 判断这些消息是否超过最大发送次数
        for (Messageinfo messageinfo : messageinfos) {
            if(messageinfo.getSequence()> maxResend ){
                //2.1 如果超过最大发送次数,将消息的状态改为Dead状态
                senderMessageInfoService.messageDead(messageinfo.getId());
            }else{
                //2.2 如果没有超过最大发送次数,将消息重新发送,不要忘记发送次数+1
                messageinfo.setSequence(messageinfo.getSequence()+1);
                //封装要发送的消息
                MessageProperties messageProperties=new MessageProperties();
                messageProperties.setHeader("sequence",messageinfo.getSequence());
                //2.3 重新发送消息时,不要忘记指定延迟时间
                messageProperties.setDelay(messageinfo.getDelaytime().intValue());
                messageProperties.setHeader("delay",messageinfo.getDelaytime().intValue());
                Message rabbitMessage=new Message(
                        messageinfo.getPayload().getBytes(StandardCharsets.UTF_8),
                        messageProperties
                );
                //使用RabbitMQ发送消息
                rabbitTemplate.convertAndSend(
                        messageinfo.getExchange(),
                        messageinfo.getRoutingkey(),
                        rabbitMessage,
                        new CorrelationData(messageinfo.getId())
                );
            }
        }
    }
}